const modal = require('./modal')
const util = require('./util')
const config = require('./config')
const schema = modal.schema
/**
 * 通过member获取下级群
 * @param memberId {string} 会员ID
 * @param parentShareRate {number} 上级的佣金
 * @returns {Promise.<void>}
 */
const getGroupByMember = async (memberId, parentShareRate) => {
  const query = schema.group().query()
  const member = schema.member()
  member.id = memberId

  query.equalTo('member', member) // 会员
  query.include('member')
  query.equalTo('status', 1) // 只查找审核通过的列表
  query.descending('updatedAt')  // 以更新时间排序
  const groups = await query.find()
  return groups.map((item) => {
    const currentGroup = util.mapAttributes(item, ['name', 'adName', 'groupCode', 'status', 'createdAt'])
    currentGroup.id = item.id
    // 会员信息
    const currentMember = item.get('member')
    currentGroup.memberId = currentMember.id
    currentGroup.memberName = currentMember.get('name')
    currentGroup.memberLevel = currentMember.get('level')
    currentGroup.memberShareRate = currentMember.get('shareRate')
    currentGroup.parentShareRate = parentShareRate
    return currentGroup
  })
}

/**
 * 通过会员查找群
 */
Parse.Cloud.define('getGroupsByMember', async (request, response) => {
  const { memberId } = request.params  // 会员ID
  if (!memberId) {
    return response.error('请提供会员ID')
  }
  try {
    response.success(await getGroupByMember(memberId))
  } catch (err) {
    response.error(err.message)
  }
})
/**
 * 查询所有群列表
 */
Parse.Cloud.define('getGroupList', async (request, response) => {
  const query = schema.group().query()
  query.equalTo('status', 1)
  try {
    const result = await query.find()
    const groupList = result.map((item) => {
      return {
        id: item.id,
        name: item.get('name')
      }
    })
    response.success(groupList)
  } catch (err) {
    response.error(err.message)
  }
})
/**
 * 通过会员查询下级群
 */
Parse.Cloud.define('getSubGroupsByMember', async (request, response) => {
  const { memberId } = request.params
  if (!memberId) {
    return response.error('请提供会员ID')
  }
  try {
    const member = schema.member()
    member.id = memberId
    const findSubMembers = util.getSubMembers(member, 2)  // 获取下级会员
    const subMembers = await findSubMembers
    let groupList = []
    // 获取下级会员的群信息
    for (let i = 0, len = subMembers.length; i < len; i++) {
      const currentSubMember = subMembers[i]
      const deep = currentSubMember.deep
      const shareRate = config.shareRate[`level${currentSubMember.level}`]
      groupList = groupList.concat(await getGroupByMember(currentSubMember.id, shareRate[`parent${deep}`]))
    }
    response.success(groupList)
  } catch (err) {
    response.error(err.message)
  }
})
/**
 * 获取群列表
 */
Parse.Cloud.define('getGroups', async (request, response) => {
  const { currentPage, pageSize, condition } = request.params
  const query = schema.group().query()
  const memberQuery = schema.member().query()
  let groupList = []

  memberQuery.equalTo('status', 1)
  query.limit(pageSize)
  query.skip((currentPage - 1) * pageSize)
  query.descending('updatedAt')  // 以更新时间排序
  query.include('member.tbk')  // 包含会员及所属淘客信息
  query.matchesQuery('member', memberQuery) // 只查询会员审核通过的群
  query.notEqualTo('status', -2) // 不查找删除的群
  // 如果含有条件
  if (condition) {
    if (condition.tbkId) {  // 如果含有淘客ID，则根据淘客ID查到对应的会员
      const tbk = schema.tbk()
      tbk.id = condition.tbkId
      const memberQuery = schema.member().query()
      memberQuery.equalTo('tbk', tbk)
      const member = await memberQuery.first()
      query.equalTo('member', member)
    }
    if (typeof condition.status === 'number') {  // 查找对应状态的群
      query.equalTo('status', condition.status)
    }
  }

  try {
    const findGroupList = query.find()
    const countGroupList = query.count()  // 统计
    const count = await countGroupList
    const groups = await findGroupList
    groupList = groups.map((item) => {
      const currentGroup = util.mapAttributes(item, ['name', 'adName', 'groupCode', 'status', 'createdAt'])
      currentGroup.id = item.id
      // 返回会员信息
      const member = item.get('member')
      currentGroup.memberId = member.id
      currentGroup.memberName = member.get('name')
      currentGroup.level = member.get('level')
      currentGroup.shareRate = member.get('shareRate')
      // 返回所属淘客信息
      const tbk = member.get('tbk')
      if (tbk) {
        currentGroup.tbkId = tbk.id
        currentGroup.tbkUsername = tbk.get('username')
      }
      return currentGroup
    })
    response.success({
      total: count,   // 总数量
      totalPage: Math.ceil(count / pageSize),  // 总页数
      currentPage,   // 当前页
      pageSize,   // 每页数量
      data: groupList
    })
  } catch (err) {
    response.error(err.message)
  }
})
/**
 * 申请建立新群
 */
Parse.Cloud.define('applyGroup', async (request, response) => {
  const { memberId, name, groupCode } = request.params
  const group = schema.group()

  const groupCodeQuery = group.query()  // 群编码重复检测
  const groupNameQuery = group.query() // 群名重复检测
  if (!memberId) {
    return response.error('请提供会员ID')
  }
  if (!name) {
    return response.error('请提供群名')
  }
  if (!groupCode) {
    return response.error('请提供群编号')
  }
  // 检测群编码及群名，避免重复
  groupCodeQuery.equalTo('groupCode', groupCode)
  groupNameQuery.equalTo('name', name)
  const findGroupCode = groupCodeQuery.first()
  const findGroupName = groupNameQuery.first()
  if (await findGroupCode) {
    return response.error('微信群编号重复')
  }
  if (await findGroupName) {
    return response.error('群名称重复')
  }
  const member = schema.member()
  member.id = memberId
  try {
    await group.save({
      member,
      name,
      groupCode,
      status: 0
    })
    response.success({
      code: 1
    })
  } catch (err) {
    response.error(err.message)
  }
})
/**
 * 更新群信息
 */
Parse.Cloud.define('updateGroup', async (request, response) => {
  const { id, name } = request.params
  if (!id) {
    return response.error('请提供群ID')
  }
  const group = schema.group()
  group.id = id
  group.set('name', name)

  try {
    await group.save()
    response.success({
      code: 1
    })
  } catch (err) {
    response.error(err.message)
  }
})
/**
 * 更新群状态
 */
Parse.Cloud.define('updateGroupStatus', async (request, response) => {
  const { id, status } = request.params
  if (!id) {
    return response.error('请提供群ID')
  }
  if (typeof status !== 'number') {
    return response.error('状态非法')
  }
  const group = schema.group()
  group.id = id

  group.set('status', status)
  try {
    await group.save()
    response.success({
      code: 1
    })
  } catch (err) {
    response.error(err.message)
  }
})
